package com.wytec.xywzxw.controller;

import com.alibaba.fastjson.JSONArray;
import com.wytec.xywzxw.bean.SendPushBean;
import com.wytec.xywzxw.bean.commonBean.CommonResult;
import com.wytec.xywzxw.utils.CommonUtils;
import com.wytec.xywzxw.utils.EmailUtils;
import com.wytec.xywzxw.utils.HardWareUtils;
import com.wytec.xywzxw.utils.JPushUtils;
import com.wytec.xywzxw.utils.excel.ExcelUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

@RestController
@Api(tags = "测试模块")
public class TestController extends BaseApiController {

    /**
     * 发件人的邮箱
     */
    @Value("${email.user}")
    private String emailSendUser;

    /**
     * 收件人的邮箱
     */
    @Value("${email.receive}")
    private String receiveUser;

    /**
     * 是否发送邮件
     */
    @Value("${email.send}")
    private boolean send;

    @Autowired
    private JPushUtils pushUtils;

    @GetMapping(value = "/push")
    @ApiOperation(value = "测试发送极光推送")
    public CommonResult<Object> push(@RequestBody SendPushBean sendPushBean) {
        pushUtils.pushWithAlias(sendPushBean);
        return CommonResult.successNoMessage();
    }

    @PostMapping(value = "/crash")
    @ApiOperation(value = "测试闪退发邮件", notes = "随边说点啥")
    public CommonResult<Object> crash(@RequestBody Map<String, String> map) {
        String content = "";
        try {
            InputStream in = new ClassPathResource("ftl/crash_notify.ftl").getInputStream();
            byte[] data = new byte[1024];
            int len;
            while ((len = in.read(data)) != -1) {
                content += new String(data, 0, len);
            }
            in.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        Map<String, String> param = new HashMap<>();
        param.put("{{crash_body}}", map.get("exception").replace("\n", "<br>"));
        param.put("{{appBuildVersion}}", map.get("appBuildVersion"));
        param.put("{{systemVersion}}", map.get("systemVersion"));
        param.put("{{bundleId}}", map.get("bundleId"));
        param.put("{{appName}}", map.get("appName"));
        param.put("{{platformVersion}}", map.get("platformVersion"));
        param.put("{{crashTime}}", map.get("crashTime"));
        param.put("{{appVersion}}", map.get("appVersion"));
        param.put("{{env}}", map.get("env"));
        param.put("{{userName}}", map.get("userName"));

        for (String key : param.keySet()) {
            content = content.replace(key, param.get(key));
        }

        //	创建Session会话
        Session session = EmailUtils.createSession();
        //	创建邮件对象
        MimeMessage message = new MimeMessage(session);
        try {
            message.setSubject("异常闪退");
            message.setFrom(new InternetAddress(emailSendUser));
            message.setRecipient(MimeMessage.RecipientType.TO, new InternetAddress(receiveUser));

            //	邮件主体
            BodyPart textPart = new MimeBodyPart();
            textPart.setContent(content, "text/html;charset=utf-8");
            Multipart multipart = new MimeMultipart();
            multipart.addBodyPart(textPart);

            //	将邮件装入信封
            message.setContent(multipart);

            //	发送
            Transport.send(message);
        } catch (Exception e) {
            e.printStackTrace();

        }

        return CommonResult.success(map);
    }


    @GetMapping("region")
    @ApiOperation("根据ip获取地理位置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ip", value = "ip地址")
    })
    private CommonResult<Object> ip2region(@RequestParam(name = "ip", required = false) String ip) {
        Map<String, String> region = CommonUtils.getIpRegion(ip);
        return CommonResult.success(region);
    }

    @GetMapping("readExcel")
    @ApiOperation("读取Excel")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "file", value = "Excel文件")
    })
    private CommonResult<Object> readExcel(@RequestPart("file") MultipartFile file) throws Exception {
        JSONArray array = ExcelUtils.readMultipartFile(file);
        System.out.println("导入数据为:" + array);
        return CommonResult.success(array);
    }

    @GetMapping("hardware")
    @ApiOperation("获取硬件信息")
    private CommonResult<Object> hardware() {
        Map<String, Object> hardware = HardWareUtils.getHardWareInfo();
        return CommonResult.success(hardware);
    }


}
